import classNames from "classnames";
import React, { createContext, ReactNode, useState } from "react"
import { TabItemProps } from "./tabItem";

type TabsSize = 'large' | 'small' | 'middle' 
type TabType = 'line' | 'card'
type TabPosition = 'top' | 'left'

export interface TabsProps {
    defaultIndex?:string;
    tabPosition?: TabPosition;
    className?: string;
    children?:ReactNode;
    size?:TabsSize;
    type?:TabType;
    onSelect?: (selectedIndex: string) => void;
}

interface TabsContext {
    index:string,
    type:string,
    onSelect?:(selectedIndex:string) => void
}


 
export const TabsContext = createContext<TabsContext>({ index:'0',type:'line' })

const Tabs = ({
    type='line',
    defaultIndex = '0',
    className,
    size,
    children,
    onSelect,
    tabPosition = 'top'
}:TabsProps) => {
    if(tabPosition === 'left' && type=== 'card') {
        return <div style={{ color:'red' }}>tabPosition do not set left when type is card</div>
    }
    const classes = classNames(className,{
        [`tabs-${tabPosition}`]: tabPosition,
        [`tabs-${size}`]: size,
        'leo-tabs':type === 'line',
        'leo-tab-item-card':type === 'card',
    })
    const classesContent = classNames('leo-tabs-content',classNames)

    const [currentActive,setActive] = useState(defaultIndex)

    // 子传父（tabItem切换将索引传过来）
    const clickFn = (index:string) => {
        console.log('index', index);
        setActive(index)
        if(onSelect) {
            onSelect(index)
        }
    }
    // 上下文参数
    const contextValue = {
        index:currentActive,
        onSelect:clickFn,
        type
    }

    const renderChildren = () => {
        return React.Children.map(children,(child,index) => {
            const childElement = child as React.FunctionComponentElement<TabItemProps>
            if(childElement.type.displayName === 'TabItem') {
                return React.cloneElement(childElement,{
                    index:index.toString()
                })
            } else {
                console.error("Warning: Tabs has a child which is not a TabItem component");
            }
        })
    } 

    const renderContent = () => {
        return React.Children.map(children, (child, index) => {
            const childElement = child as React.FunctionComponentElement<TabItemProps>
            if(index.toString() === currentActive) {
                return childElement.props.children
                
            }
        })
    }

    return (
        <div className={tabPosition === 'top' ? 'leo-tabs-wrapper' : 'leo-tabs-wrapper-left'}>
            <TabsContext.Provider value={contextValue}>
                <ul className={classes}>
                    { renderChildren() }
                </ul>
            </TabsContext.Provider>
            <div className={classesContent}>
                { renderContent()}
            </div>
        </div>   
    )
 }

 export default Tabs